package cn.tedu.serviceEdu.listener;

import cn.tedu.serviceBase.exception.EducationException;
import cn.tedu.serviceEdu.entity.EduSubject;
import cn.tedu.serviceEdu.entity.excel.SubjectData;
import cn.tedu.serviceEdu.service.EduSubjectService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.Map;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    public EduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }


    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new EducationException(20001, "excel文件数据为空");
        }
        EduSubject oneSubject = this.duplicatedOneSubject(subjectData.getOneSubjectName(), subjectService);
        if (oneSubject == null) {
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(oneSubject);
        }
        String oneSubjectId = oneSubject.getId();
        EduSubject twoSubject = this.duplicatedTwoSubject(subjectData.getOneSubjectName(), oneSubjectId, subjectService);
        if (twoSubject == null) {
            twoSubject = new EduSubject();
            twoSubject.setParentId(oneSubjectId);
            twoSubject.setTitle(subjectData.getTowSubjectName());
            subjectService.save(twoSubject);
        }
    }


    private EduSubject duplicatedOneSubject(String name, EduSubjectService subjectService) {
        LambdaQueryWrapper<EduSubject> lqw = new LambdaQueryWrapper<>();
        lqw.eq(EduSubject::getTitle, name);
        lqw.eq(EduSubject::getParentId, "0");
        return subjectService.getOne(lqw);
    }

    private EduSubject duplicatedTwoSubject(String name, String parentId, EduSubjectService subjectService) {
        LambdaQueryWrapper<EduSubject> lqw = new LambdaQueryWrapper<>();
        lqw.eq(EduSubject::getTitle, name);
        lqw.eq(EduSubject::getParentId, parentId);
        return subjectService.getOne(lqw);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

}
